package com.detrum.sportcamera.runnable;

import android.util.Log;

import com.detrum.base.BaseStatic;
import com.detrum.utils.DeviceFinal;
import com.detrum.utils.LogUtils;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.TimeoutException;

/**
 * Created by abc on 2017/12/1.
 */

public class SendRunnable implements Runnable {
    byte[] data;
    DatagramSocket socket;

    public SendRunnable(byte[] data, DatagramSocket socket) {
        if (this.data != null) {
            this.data = null;
        }
        this.data = data;
        this.socket = socket;
    }

    @Override
    public void run() {
        InetAddress serverAddress = null;
        try {
            serverAddress = InetAddress.getByName(BaseStatic.DHCP_SERVICE_IP);
            //创建一个DatagramPacket对象，用于发送数据。
            //参数一：要发送的数据  参数二：数据的长度  参数三：服务端的网络地址  参数四：服务器端端口号
            if(data==null){
                return;
            }
            DatagramPacket inPacket = new DatagramPacket(data, data.length, serverAddress, DeviceFinal.SEND_DATA_PORT);
            LogUtils.e(inPacket.getSocketAddress().toString());
            if(socket!=null){
                socket.send(inPacket);//把数据发送到服务端。底层有同步这里不需要再做
            }
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
